<?php
/**
 * 注册文件
 *
 * @author lwb
 */

namespace app\wechat\controller;
use Overtrue\EasySms\EasySms;

class Register extends Common {
// 保存错误信息
    public $error;
// Access Key ID
    private $accessKeyId = 'LTAIGVSQeT4KxosQ';
// Access Access Key Secret
    private $accessKeySecret = '6lWbaFakgFFOYIAPeQlZfZNo2PRLx4';
// 签名
    private $signName = '蚂蚁白领';
// 模版ID
    private $templateCode = 'SMS_197920070';
//    public function initialize(){
//        parent::_initialize();
//        $cofig = array (
//            'accessKeyId' => 'LTAIGVSQeT4KxosQ',
//            'accessKeySecret' => '6lWbaFakgFFOYIAPeQlZfZNo2PRLx4',
//            'signName' => '蚂蚁白领',
//            'templateCode' => 'SMS_197920070'
//        );
//// 配置参数
//        $this->accessKeyId = $cofig ['accessKeyId'];
//        $this->accessKeySecret = $cofig ['accessKeySecret'];
//        $this->signName = $cofig ['signName'];
//        $this->templateCode = $cofig ['templateCode'];
//    }

    /*
     * 注册/重置密码
     */
    public function register($params) {
        if(!session('partner_id') && !session('b_id')){
            return $this->parse_data(['code' => 5000, 'msg' => '非法操作']);
        }
        if (strlen($params['password']) < 6 || strlen($params['password']) >= 20) {
            return $this->parse_data(['code' => 5000, 'msg' => '请输入6-20位长度密码']);
        }
        if ($params['password'] <> $params['password2']) {
            return $this->parse_data(['code' => 5000, 'msg' => '两次密码不一致，请重新输入']);
        }
        if (empty($params['code']) || (cookie($params['username']) <> $params['code'])) {
            return $this->parse_data(['code' => 5000, 'msg' => '短信验证码不正确，请重新输入']);
        }
        if(session('partner_id')){
            $result = $this->getWS('ucenter', 'users@reg', ['userName' => $params['username'], 'userPwd' => $params['password'], 'openId' => session('openid')]);
        
            if($result['status'] != '2000'){
                return $this->parse_data(['code' => 5000, 'msg' => $result['msg']]);
            }
        }else{
            $result = $this->getWS('ucenter', 'users@resetPwd', ['userName' => $params['username'], 'newPwd' => $params['password'], 'openId' => session('openid')]);
        
            if($result['status'] != '2000'){
                return $this->parse_data(['code' => 5000, 'msg' =>  $result['msg']]);
            }
        }
        
        cookie($params['username'],null);
        session('uid', $result['result']['u_code']);
        session('username', $params['username']);
        if(session('partner_id')){
            if(session('order_price')){
                $jump_url = '/user/authform?order_price='.session('order_price');
            }else{
                $jump_url = '/user/authform';
            }
        }else{
            $jump_url = '/user/submitmsg';
        }
        return $this->parse_data(['data' => ['jumpUrl' => $jump_url]]);
    }
    
    /*
     * 重置密码
     */
    public function resetPwd($params) {
        if (strlen($params['password']) < 6 || strlen($params['password']) >= 20) {
            return $this->parse_data(['code' => 5000, 'msg' => '请输入6-20位长度密码']);
        }
        if ($params['password'] <> $params['password2']) {
            return $this->parse_data(['code' => 5000, 'msg' => '两次密码不一致，请重新输入']);
        }
        if (empty($params['code']) || (cookie($params['username']) <> $params['code'])) {
            return $this->parse_data(['code' => 5000, 'msg' => '短信验证码不正确，请重新输入']);
        }

        $result = $this->getWS('ucenter', 'users@resetPwd', ['userName' => $params['username'], 'newPwd' => $params['password']]);

        if($result['status'] != '2000'){
            return $this->parse_data(['code' => 5000, 'msg' =>  $result['msg']]);
        }
        
        cookie($params['username'],null);
        session('uid', $result['result']['u_code']);
        session('username', $params['username']);

        return $this->parse_data();
    }

    /*
     * 发送验证码
     */
    public function sendcode($params) {
        $code = rand(1000, 9999);
//        $result=$this->sendSms($params['phone'],$code);
//        $result=$this->lssms($params['phone'],$code);
        $result = $this->send_verify($params['phone'], $code);
//        if(intval($params['type'])){
//            $result = $this->getWS('channel', 'message@send', ['tplName' => 'R001', 'phone' => $params['phone'], 'param' => ['code' => $code]]);
//        }else{
//            $result = $this->getWS('channel', 'message@send', ['tplName' => 'R002', 'phone' => $params['phone'], 'param' => ['code' => $code]]);
//        }
//        var_dump($result);die;
        if($result['Code']=='OK'){
            cookie($params['phone'], $code, '300');
            return $this->parse_data();
        }else{
            return $this->parse_data(['code' => 5000, 'msg' => '发送失败']);
        }

    }
//
//    public function lssms($phone,$code){
//        $content  = $code.'验证码，5分钟内有效。';
//        $url="http://smssh1.253.com/msg/send/json";//模板消息请求URL
//        $data=array(
//            'account'=>'N1776266',
//            'password'=>'70Kud6irT',
//            'msg'=>$content,
//            'phone'=>$phone
//        );
//        $res=$this->post($url,$data);
//        return $res;
//    }
//
//
//// new 临时发短信
//    function post($url, $post_data = [])
//    {
//        if (empty($post_data) || empty($url)) {
//            return false;
//        }
//        $ch = curl_init();
//        $data_string = json_encode($post_data);
//        curl_setopt($ch, CURLOPT_URL, $url);
//        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//        //post数据
//        curl_setopt($ch, CURLOPT_POST, 1);
//        //post的变量
//        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
//        //加入以下设置
//        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($data_string)));
//        $output = curl_exec($ch);
//        curl_close($ch);
//        //打印获得的数据
//        return json_decode($output,True);
//    }
//



    /**
     * 阿里云短信验证码发送类
     * @author Administrator
     *
     */

    private function percentEncode($string) {
        $string = urlencode ( $string );
        $string = preg_replace ( '/\+/', '%20', $string );
        $string = preg_replace ( '/\*/', '%2A', $string );
        $string = preg_replace ( '/%7E/', '~', $string );
        return $string;
    }
    /**
     * 签名
     *
     * @param unknown $parameters
     * @param unknown $accessKeySecret
     * @return string
     */
    private function computeSignature($parameters, $accessKeySecret) {
        ksort ( $parameters );
        $canonicalizedQueryString = '';
        foreach ( $parameters as $key => $value ) {
            $canonicalizedQueryString .= '&' . $this->percentEncode ( $key ) . '=' . $this->percentEncode ( $value );
        }
        $stringToSign = 'GET&%2F&' . $this->percentencode ( substr ( $canonicalizedQueryString, 1 ) );
        $signature = base64_encode ( hash_hmac ( 'sha1', $stringToSign, $accessKeySecret . '&', true ) );
        return $signature;
    }

    /**
     * @param unknown $mobile
     * @param unknown $verify_code
     *
     */

    public function send_verify($mobile, $verify_code) {
        $params = array ( //此处作了修改
            'SignName' => $this->signName,
            'Format' => 'JSON',
            'Version' => '2017-05-25',
            'AccessKeyId' => $this->accessKeyId,
            'SignatureVersion' => '1.0',
            'SignatureMethod' => 'HMAC-SHA1',
            'SignatureNonce' => uniqid (),
            'Timestamp' => gmdate ( 'Y-m-d\TH:i:s\Z' ),
            'Action' => 'SendSms',
            'TemplateCode' => $this->templateCode,
            'PhoneNumbers' => $mobile,
            'TemplateParam' => '{"code":"' . $verify_code . '"}'
        );
        $params ['Signature'] = $this->computeSignature ( $params, $this->accessKeySecret );
        $url = 'http://dysmsapi.aliyuncs.com/?' . http_build_query ( $params );
        $ch = curl_init ();
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_TIMEOUT, 10 );
        $result = curl_exec ( $ch );
        curl_close ( $ch );
        $result = json_decode ( $result, true );
        return $result;
    }

    /**
     * 获取详细错误信息
     *
     * @param unknown $status
     */
    public function getErrorMessage($status) {
        $message = array (
            'InvalidDayuStatus.Malformed' => '账户短信开通状态不正确',
            'InvalidSignName.Malformed' => '短信签名不正确或签名状态不正确',
            'InvalidTemplateCode.MalFormed' => '短信模板Code不正确或者模板状态不正确',
            'InvalidRecNum.Malformed' => '目标手机号不正确，单次发送数量不能超过100',
            'InvalidParamString.MalFormed' => '短信模板中变量不是json格式',
            'InvalidParamStringTemplate.Malformed' => '短信模板中变量与模板内容不匹配',
            'InvalidSendSms' => '触发业务流控',
            'InvalidDayu.Malformed' => '变量不能是url，可以将变量固化在模板中'
        );
        if (isset ( $message [$status] )) {
            return $message [$status];
        }
        return $status;
    }




    /**
     * Desc: 检测手机号是否为重复手机号
     * User: liuning
     * Date: 2018/11/28 20:40
     * Return: array
     * Update:
     */
    public function checkPhoneRepeat($params) {
        $result = $this->getWS('credit', 'Partners@check_phone_repeat', ['phone' => $params['phone']]);
        if ($result['status'] == '2000') {
            return $this->parse_data(['code' => 2000, 'msg' => '手机号重复，请更换手机号']);
        }else{
            return $this->parse_data(['code' => 5000, 'msg' => '手机号验证成功']);
        }
    }

    /*
     * 注册
     */
    public function payRegister($params) {
        if (strlen($params['password']) < 6 || strlen($params['password']) >= 20) {
            return $this->parse_data(['code' => 5000, 'msg' => '请输入6-20位长度密码']);
        }
        if ($params['password'] <> $params['password2']) {
            return $this->parse_data(['code' => 5000, 'msg' => '两次密码不一致，请重新输入']);
        }
        if (empty($params['code']) || (cookie($params['username']) <> $params['code'])) {
            return $this->parse_data(['code' => 5000, 'msg' => '短信验证码不正确，请重新输入']);
        }

        $result = $this->getWS('ucenter', 'users@reg', ['userName' => $params['username'], 'userPwd' => $params['password'], 'openId' => session('openid')]);

        if($result['status'] != '2000'){
            return $this->parse_data(['code' => 5000, 'msg' => $result['msg']]);
        }

        cookie($params['username'],null);
        session('uid', $result['result']['u_code']);
        session('username', $params['username']);

        if(session('p_id')){
            $jump_url = '/confirmOrder?p_id='.session('p_id');//待付款页面
        }else{
            $jump_url = '/payIndex';//H5入口
        }
        return $this->parse_data(['data' => ['jumpUrl' => $jump_url]]);
    }

    /*
    * 机构注册
    */
    public function partnerRegister($params) {
        if (!preg_match('/^[A-Za-z0-9_]+$/', $params['a_name'])) {
            return $this->parse_data(['code' => 5000, 'msg' => '用户名限定字母、数字或下划线的组合']);
        }
        if (strlen($params['password']) < 6 || strlen($params['password']) >= 20) {
            return $this->parse_data(['code' => 5000, 'msg' => '请输入6-20位长度密码']);
        }
        if ($params['password'] <> $params['password2']) {
            return $this->parse_data(['code' => 5000, 'msg' => '两次密码不一致，请重新输入']);
        }
        if (empty($params['code']) || (cookie($params['partner_contact_phone']) <> $params['code'])) {
            return $this->parse_data(['code' => 5000, 'msg' => '短信验证码不正确，请重新输入']);
        }
        $params       = $this->xaddslashes($params);

        $registerData = array(
            'partner_name' => $params['partner_name'],
            'partner_short_name' => $params['partner_short_name'],
            'partner_people_level' => $params['partner_people_level'],
            'partner_contact_name' => $params['partner_contact_name'],
            'partner_contact_phone' => $params['partner_contact_phone'],
            'a_name' => $params['a_name'],
            'password' => $params['password'],
            'password2' => $params['password2'],
            'code' => $params['code'],
            'director' => $params['director'],
            're_name' => $params['re_name'],
            're_phone' => $params['re_phone'],
        );

        $result = $this->getWS('credit', 'Partners@registerPartner', $registerData);

        if($result['status'] != '2000'){
            return $this->parse_data(['code' => $result['status'], 'msg' => $result['msg']]);
        }

        $jump_url = config("admin_logout_url");//后台注册后退出
        return $this->parse_data(['code' => 2000, 'msg' => '注册成功','data' => ['jumpUrl' => $jump_url]]);
    }


}
